/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { ApiRole } from "_common/api/sys";
import { ApiUser } from "_common/api/sys/ApiUser";
import { DrawerProps } from "_common/DataType";
import { SysRole, SysUser } from "_common/entity";
import React, { useState, useEffect, useRef } from "react";
import {
  Button,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  Select,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
type UserDrawerProps = DrawerProps & {};
const UserDrawer: React.FC<UserDrawerProps> = (props: UserDrawerProps) => {
  const { open, axios, edit, onSuccess, value } = props;
  const formRef = useRef<FormInstanceFunctions>();

  // 角色列表状态
  const [roleList, setRoleList] = useState<SysRole[]>([]);
  const apiUser = new ApiUser(axios!);
  const apiRole = new ApiRole(axios!);
  useEffect(() => {
    getRoleList();
    return () => {
      formRef.current?.reset();
    };
  }, []);

  useEffect(() => {
    if (value && edit) {
      formRef.current?.setFieldsValue(value);
    }
    getUserRoleIds();
  }, [edit, value]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
  };

  // 新增用户
  const createUser = async (data: SysUser) => {
    const response = await apiUser.createUser(data);
    if (response && response.code == 200 && response.data) {
      handleClose();
    }
  };
  // 更新用户
  const updateUser = async (data: SysUser) => {
    const response = await apiUser.updateUser({
      ...data,
      id: value?.id,
    });
    if (response && response.code == 200 && response.data) {
      handleClose();
    }
  };

  // 获取角色列表
  const getRoleList = async () => {
    const response = await apiRole.getRoleList();
    if (response && response.code == 200 && response.data) {
      setRoleList(response.data);
    }
  };

  // 获取当前用户的角色ids
  const getUserRoleIds = async () => {
    if (!value) return;
    const response = await apiUser.getUserRoleIds(value.id);
    if (response && response.code == 200 && response.data) {
      formRef.current?.setFieldsValue({
        roles: response.data,
      });
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}用户`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        ref={formRef}
        labelWidth={100}
        onSubmit={async (data) => {
          // 是否校验通过
          if ((await formRef.current?.validateOnly()) == true) {
            edit
              ? updateUser(data.fields as SysUser)
              : createUser(data.fields as SysUser);
          }
        }}
      >
        <FormItem label="登录账号" rules={[{ required: true }]} name="account">
          <Input readonly={edit} />
        </FormItem>
        <FormItem
          label="登录密码"
          rules={[
            {
              required: true,
            },
            { min: 6, message: "密码为数字+字母，最少6位" },
          ]}
          name="password"
        >
          <Input type="password" placeholder="密码为数字+字母，最少6位" />
        </FormItem>
        <FormItem label="用户名称" rules={[{ required: true }]} name="name">
          <Input />
        </FormItem>
        <FormItem label="性别" rules={[{ required: false }]} name="gender">
          <Select
            options={[
              { label: "男", value: "1" },
              { label: "女", value: "2" },
            ]}
          />
        </FormItem>
        <FormItem
          label="邮箱"
          rules={[{ pattern: /@/, message: "请输入 正确的邮箱地址" }]}
          name="email"
        >
          <Input />
        </FormItem>
        <FormItem label="角色" name="roles">
          <Select
            multiple
            options={roleList?.map((item) => ({
              label: item.name,
              value: item.id,
            }))}
          />
        </FormItem>
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default UserDrawer;
